package com.dongdongshop.controller;

import com.dongdongshop.data.Result;
import com.dongdongshop.enums.ResultEnum;
import com.dongdongshop.exception.LoginException;
import com.dongdongshop.pojo.TbSeller;
import com.dongdongshop.service.TbSellerService;
import com.dongdongshop.shiro.ShiroUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("sellerLogin")
public class SellerLoginController {

    private Logger logger = LoggerFactory.getLogger(SellerLoginController.class);

    @DubboReference
    private TbSellerService sellerService;
    @RequestMapping("toLogin")
    public String toLogin(){
        return "shoplogin";
    }

    @RequestMapping("toRegister")
    public String toRegister(){
        return "register";
    }
    @RequestMapping("index")
    public String index(){
        return "admin/index";
    }
    @RequestMapping("home")
    public String home(){
        return "admin/home";
    }

    @RequestMapping("register")
    @ResponseBody
    public Result register(TbSeller tbSeller){
        try {
            String salt = ShiroUtils.generateSalt(6);
            String s = ShiroUtils.encryptPassword("MD5", tbSeller.getPassword(), salt, 3);
            TbSeller seller = sellerService.selectSellerById(tbSeller.getSellerId());
            if (seller != null){
                return Result.response(ResultEnum.REGISTER_MESSAGE_ERROE);
            }
            tbSeller.setSalt(salt);
            tbSeller.setPassword(s);
            tbSeller.setStatus("0");
            sellerService.addSeller(tbSeller);
            return Result.OK();
        }catch (Exception e){
            logger.info("批量删除方法异常 {}",e.toString());
            return Result.response(ResultEnum.DELETE_MESSAGE_ERROE);
        }
    }

    @RequestMapping("login")
    @ResponseBody
    public Result login(String sellerId,String password){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(sellerId, password);
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            return Result.response(ResultEnum.LOGIN_USERNAME_NULL);
        } catch (IncorrectCredentialsException e) {
            return Result.response(ResultEnum.LOGIN_PASSWORD_ERROR);
        } catch (LoginException e){
            return Result.response(ResultEnum.AUDIT_MESSAGE_LOGIN_KILL);
        }
        return Result.OK();
    }
}
